<?php
declare (strict_types=1);

namespace app\admin\logic\market\advert;

use app\admin\logic\system\Log;
use app\admin\model\market\advert\Advert as AdvertModel;
use app\admin\model\market\advert\AdvertPlace;
use app\common\exception\LogicException;

/**
 * 广告图配置模型
 */
class Advert extends AdvertModel
{
    /**
     * 获取列表
     * Author   Martinsun<syh@sunyonghong.com>
     * Date 2020-05-25
     *
     * @return   [type]                         [description]
     */
    public function getList(array $map = [])
    {
        $where = $map['__TABLE__'];

        return $this->alias('Advert')->with(['place'])->hasWhere('place', $map['place'])->where($where)->order('update_time', 'DESC')->paginate($this->getListRows());
    }

    /**
     * 新建广告
     * Author   Martinsun<syh@sunyonghong.com>
     * Date 2020-06-22
     *
     * @param array $data [description]
     * @return   [type]                               [description]
     */
    public function createAdvert(array $data)
    {
        // 验证数据
        $this->getValidate()->scene('create')->failException()->check($data);

        $save = [
            'place'  => $data['place'],
            'remark' => $data['remark'] ?? '',
        ];

        if (!$this->save($save)) {
            throw new LogicException('添加失败');
        }

        $place  = $save['place'];
        $mhm_id = request()->mhm_id;
        $key    = app(AdvertPlace::class)->where('id', $place)->value('key');
        cache("advert_" . $mhm_id . '_' . $key, null);

        $title = AdvertPlace::where('id', $data['place'])->value('title');
        Log::write('新建广告位【' . $title . '】', 'advert', 'create', true);

        return $this;
    }

    /**
     * 编辑广告
     * Author   Martinsun<syh@sunyonghong.com>
     * Date 2020-05-20
     *
     * @param    [type]                         $id   [description]
     * @param    [type]                         $data [description]
     * @return   [type]                               [description]
     */
    public function editAdvert($id, $data)
    {
        $advert = $this->where('id', $id)->findOrFail();

        $check       = $data;
        $check['id'] = $id;
        // 验证数据
        $this->getValidate()->scene('edit')->failException()->check($check);

        $advert->place = $data['place'];
        // $advert->status = $data['status'];
        $advert->remark = $data['remark'];
        if (!$advert->save()) {
            throw new LogicException('更新失败');
        }

        $place  = $advert->place;
        $mhm_id = $advert->mhm_id;
        $key    = app(AdvertPlace::class)->where('id', $place)->value('key');
        cache("advert_" . $mhm_id . '_' . $key, null);

        $title = AdvertPlace::where('id', $data['place'])->value('title');
        Log::write('更新广告位【' . $title . '】', 'advert', 'update', true);

        return $advert;
    }

    /**
     * 更新某个字段值
     * Author   Martinsun<syh@sunyonghong.com>
     * Date 2020-05-25
     *
     * @param    [type]                         $id    [description]
     * @param    [type]                         $field [description]
     * @param    [type]                         $value [description]
     * @return   [type]                                [description]
     */
    public function updateField(int $id, string $field, $value)
    {
        $advert         = $this->where('id', $id)->findOrFail();
        $advert->$field = $value;

        if (!$advert->save()) {
            throw new LogicException('操作失败');
        }

        $place  = $advert->place;
        $mhm_id = $advert->mhm_id;
        $key    = app(AdvertPlace::class)->where('id', $place)->value('key');
        cache("advert_" . $mhm_id . '_' . $key, null);

        $title = AdvertPlace::where('id', $advert->place)->value('title');
        Log::write('更新广告位【' . $title . '】', 'advert', 'update', true);

        return $advert;

    }

    /**
     * 获取可选的广告位
     * Author   Martinsun<syh@sunyonghong.com>
     * Date 2020-06-22
     *
     * @return   [type]                         [description]
     */
    public function getAdvertPlaceOptions($exclude_ids = [])
    {
        $exclude_ids = is_array($exclude_ids) ? $exclude_ids : explode(',', (string)$exclude_ids);
        // 获取当前已经配置的广告位
        $ids = $this->column('place');
        $ids = array_diff($ids, $exclude_ids);
        if (request()->is_platform) {
            $data = AdvertPlace::whereNotIn('id', $ids)->whereIn('attributes', '1,2')->column('title', 'id');
        } else {
            $data = AdvertPlace::whereNotIn('id', $ids)->whereIn('attributes', '1,3')->column('title', 'id');
        }

        $options = [];

        foreach ($data as $key => $title) {
            $options[] = [
                'value' => $key,
                'title' => $title,
            ];
        }

        return $options;
    }

    /**
     * 删除广告
     * Author   Martinsun<syh@sunyonghong.com>
     * Date 2020-05-20
     *
     * @param    [type]                         $id [description]
     * @return   [type]                             [description]
     */
    public function deleteAdvert($id)
    {
        $advert = $this->where('id', $id)->findOrFail();
        $place  = $advert->place;
        $mhm_id = $advert->mhm_id;

        if (!$advert->delete()) {
            throw new LogicException("删除失败");
        }

        $key = app(AdvertPlace::class)->where('id', $place)->value('key');
        cache("advert_" . $mhm_id . '_' . $key, null);

        $title = AdvertPlace::where('id', $advert->place)->value('title');
        Log::write('删除广告位【' . $title . '】', 'advert', 'delete', true);
    }

    /**
     * 获取广告位类型
     *
     * @param $id
     * @return int 0: 未知 1: PC  2: 手机端
     */
    public function getPlaceType($id)
    {
        $type  = 0;
        $place = $this->where('id', $id)->value('place');
        if ($place) {
            $key = app(AdvertPlace::class)->where('id', $place)->value('key');
            // 匹配是否pc.开头的关键字
            if (preg_match('/^pc\./', $key)) {
                $type = 1;
            } else {
                $type = 2;
            }
        }

        return $type;
    }

}
